<template>
	<div class="home-container">
		<!-- 增加顶部导出按钮工具栏 -->
		<div class="chart-export-toolbar">
			<el-button type="primary" @click="exportAllCharts">
				<i class="iconfont icon-download"></i> 导出所有图表
			</el-button>
			<el-dropdown @command="handleExportCommand">
				<el-button type="success">
					<span>导出单个图表</span>
					<el-icon class="el-icon--right"><ele-ArrowDown /></el-icon>
				</el-button>
				<template #dropdown>
					<el-dropdown-menu>
						<el-dropdown-item command="line">销售业绩趋势图</el-dropdown-item>
						<el-dropdown-item command="pie">生产计划完成情况图</el-dropdown-item>
						<el-dropdown-item command="bar">已完成订单金额统计图</el-dropdown-item>
					</el-dropdown-menu>
				</template>
			</el-dropdown>
		</div>
		<el-row :gutter="15" class="home-card-one mb15">
			<el-col
				:xs="24"
				:sm="12"
				:md="12"
				:lg="6"
				:xl="6"
				v-for="(v, k) in homeOne"
				:key="k"
				:class="{ 'home-media home-media-lg': k > 1, 'home-media-sm': k === 1 }"
			>
				<div class="home-card-item flex">
					<div class="flex-margin flex w100" :class="` home-one-animation${k}`">
						<div class="flex-auto">
							<span class="font30">{{ v.num1 }}</span>
							<span class="ml5 font16" :style="{ color: v.color1 }">{{ v.num2 }}%</span>
							<div class="mt10">{{ v.num3 }}</div>
						</div>
						<div class="home-card-item-icon flex" :style="{ background: `var(${v.color2})` }">
							<i class="flex-margin font32" :class="v.num4" :style="{ color: `var(${v.color3})` }"></i>
						</div>
					</div>
				</div>
			</el-col>
		</el-row>
		<el-row :gutter="15" class="home-card-two mb15">
			<el-col :xs="24" :sm="14" :md="14" :lg="16" :xl="16">
				<div class="home-card-item">
					<div style="height: 100%" ref="homeLineRef"></div>
				</div>
			</el-col>
			<el-col :xs="24" :sm="10" :md="10" :lg="8" :xl="8" class="home-media">
				<div class="home-card-item">
					<div style="height: 100%" ref="homePieRef"></div>
				</div>
			</el-col>
		</el-row>
		<el-row :gutter="15" class="home-card-three">
			<el-col :xs="24" :sm="10" :md="10" :lg="8" :xl="8">
				<div class="home-card-item">
					<div class="home-card-item-title">快捷导航工具</div>
					<div class="home-monitor">
						<div class="flex-warp">
							<div class="flex-warp-item" v-for="(v, k) in homeThree" :key="k">
								<div class="flex-warp-item-box" :class="`home-animation${k}`" @click="handleNavClick(v.path)">
									<div class="flex-margin">
										<i :class="v.icon" :style="{ color: v.iconColor }"></i>
										<span class="pl5">{{ v.label }}</span>
										<div class="mt10">{{ v.value }}</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</el-col>
			<el-col :xs="24" :sm="14" :md="14" :lg="16" :xl="16" class="home-media">
				<div class="home-card-item">
					<div style="height: 400px" ref="homeBarRef"></div>
				</div>
			</el-col>
			
		</el-row>
	</div>
</template>

<script lang="ts">
import { toRefs, reactive, defineComponent, onMounted, ref, watch, nextTick, onActivated, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import { useTagsViewRoutes } from '/@/stores/tagsViewRoutes';
import { GetList as getSalesPerformance } from '/@/views/sales/performance/api';
import { GetList as getProductionPlan } from '/@/views/produce/ProductionPlan/api';
import { GetList as getMaterialList } from '/@/views/inventory/material/api';
import { GetList as getSupplierList } from '/@/views/supplier/supplier/api';
import { GetList as getDeptList } from '/@/views/system/dept/api';
import { GetList as getDeviceList } from '/@/views/device/Device/api';
import { GetList as getUserList } from '/@/views/system/user/api';
import { GetList as getMaintenanceList } from '/@/views/device/MaintenanceRecord/api';
import { GetList as getBudgetList } from '/@/views/finance/budget/api';
import { GetList as getSupplierProductList } from '/@/views/supplier/SupplierProduct/api';
import { GetList as getOrderList } from '/@/views/order/Order/api';
import { GetList as getPurchasePlanList } from '/@/views/purchase/PurchasePlan/api';
import { useRouter } from 'vue-router';
import { ElNotification, ElMessage } from 'element-plus';

// 初始化全局变量
let global: any = {
	homeChartOne: null,
	homeChartTwo: null,
	homeChartThree: null,
};

export default defineComponent({
	name: 'home',
	setup() {
		const router = useRouter();
		const homeLineRef = ref();
		const homePieRef = ref();
		const homeBarRef = ref();
		const storesTagsViewRoutes = useTagsViewRoutes();
		const storesThemeConfig = useThemeConfig();
		const { themeConfig } = storeToRefs(storesThemeConfig);
		const { isTagsViewCurrenFull } = storeToRefs(storesTagsViewRoutes);
		const state = reactive({
			orderData: [] as any[],
			homeOne: [
				{
					num1: '0',
					num2: '0',
					num3: '订单统计信息',
					num4: 'fa fa-meetup',
					color1: '#FF6462',
					color2: '--next-color-primary-lighter',
					color3: '--el-color-primary',
				},
				{
					num1: '0',
					num2: '0',
					num3: '月度计划信息',
					num4: 'iconfont icon-ditu',
					color1: '#6690F9',
					color2: '--next-color-success-lighter',
					color3: '--el-color-success',
				},
				{
					num1: '0',
					num2: '0',
					num3: '年度计划信息',
					num4: 'iconfont icon-zaosheng',
					color1: '#6690F9',
					color2: '--next-color-warning-lighter',
					color3: '--el-color-warning',
				},
				{
					num1: '0',
					num2: '0',
					num3: '访问统计信息',
					num4: 'fa fa-github-alt',
					color1: '#FF6462',
					color2: '--next-color-danger-lighter',
					color3: '--el-color-danger',
				},
			],
			homeThree: [
				{
					icon: 'iconfont icon-order',
					label: '本月销售额',
					value: '0',
					iconColor: '#F72B3F',
					path: '/sales/performance'
				},
				{
					icon: 'iconfont icon-production',
					label: '生产计划',
					value: '0',
					iconColor: '#91BFF8',
					path: '/produce/plan'
				},  
				{
					icon: 'iconfont icon-equipment',
					label: '设备数量',
					value: '0',
					iconColor: '#FBD4A0',
					path: '/device/Device'
				},
				{
					icon: 'iconfont icon-finance',
					label: '财务统计',
					value: '0',
					iconColor: '#FBD4A0',
					path: '/finance/budget'
				},
				{
					icon: 'iconfont icon-maintenance',
					label: '待审批设备',
					value: '0',
					iconColor: '#FBD4A0',
					path: '/device/MaintenanceRecord'
				},
				{
					icon: 'iconfont icon-purchase',
					label: '待审批采购',
					value: '0',
					iconColor: '#4CAF50',
					path: '/purchase/plan'
				},
				{
					icon: 'iconfont icon-supplier',
					label: '供应商数量',
					value: '0',
					iconColor: '#87CEEB',
					path: '/supplier/supplier'
				},
				{
					icon: 'iconfont icon-goods',
					label: '供应商商品',
					value: '0',
					iconColor: '#98FB98',
					path: '/supplier/product'
				},
			],
			myCharts: [],
			charts: {
				theme: '',
				bgColor: '',
				color: '#303133',
			},
			salesData: {
				monthly: [] as any[],
				yearly: [] as any[],
			},
			productionData: {
				monthly: [] as any[],
				yearly: [] as any[],
			},
			
			materialData: [] as any[],
			supplierData: [] as any[],
			supplierProductData: [] as any[],
			deptData: [] as any[],
			deviceData: [] as any[],
			userData: [] as any[],
			maintenanceData: [] as any[],
			budgetData: [] as any[],
			purchasePlanData: [] as any[],
		});

		// 获取部门数据
		const loadDeptData = async () => {
			try {
				const res = await getDeptList({
					page: 1,
					limit: 9999
				});
				if (res.data) {
					state.deptData = res.data;
					updateHomeThree();
				}
			} catch (error) {
				console.error('加载部门数据失败:', error);
			}
		};

		// 获取供应商数据
		const loadSupplierData = async () => {
			try {
				const [supplierRes, productRes] = await Promise.all([
					getSupplierList({
						page: 1,
						limit: 9999
					}),
					getSupplierProductList({
						page: 1,
						limit: 9999
					})
				]);
				if (supplierRes.data) {
					state.supplierData = supplierRes.data;
					state.supplierProductData = productRes.data || [];
					updateHomeThree();
				}
			} catch (error) {
				console.error('加载供应商数据失败:', error);
			}
		};

		// 获取设备数据
		const loadDeviceData = async () => {
			try {
				const res = await getDeviceList({
					page: 1,
					limit: 9999
				});
				if (res.data) {
					state.deviceData = res.data;
					updateHomeThree();
				}
			} catch (error) {
				console.error('加载设备数据失败:', error);
			}
		};

		// 获取员工数据
		const loadUserData = async () => {
			try {
				const res = await getUserList({
					page: 1,
					limit: 9999
				});
				if (res.data) {
					state.userData = res.data;
					updateHomeThree();
				}
			} catch (error) {
				console.error('加载员工数据失败:', error);
			}
		};

		// 获取设备维护记录数据
		const loadMaintenanceData = async () => {
			try {
				const res = await getMaintenanceList({
					page: 1,
					limit: 9999
				});
				if (res.data) {
					state.maintenanceData = res.data;
					updateHomeThree();
				}
			} catch (error) {
				console.error('加载设备维护记录数据失败:', error);
			}
		};

		// 获取财务预算数据
		const loadBudgetData = async () => {
			try {
				const res = await getBudgetList({
					page: 1,
					limit: 9999
				});
				if (res.data) {
					state.budgetData = res.data;
					updateHomeThree();
				}
			} catch (error) {
				console.error('加载财务预算数据失败:', error);
			}
		};

		// 获取采购计划数据
		const loadPurchasePlanData = async () => {
			try {
				console.log('开始加载采购计划数据...');
				const res = await getPurchasePlanList({
					page: 1,
					limit: 9999,
					status: 0  // 显式筛选待审批状态
				});
				
				if (res && res.data) {
					console.log('采购计划API响应:', res);
					state.purchasePlanData = Array.isArray(res.data) ? res.data : (res.data.data || []);
					
					// 分析数据，确认状态值的类型
					if (state.purchasePlanData.length > 0) {
						const firstItem = state.purchasePlanData[0];
						console.log('采购计划第一条数据:', firstItem);
						console.log('采购计划状态类型:', typeof firstItem.status, '值:', firstItem.status);
					}
					
					// 计算待审批数量
					const pendingCount = state.purchasePlanData.filter(item => item.status === 0).length;
					console.log('成功加载采购计划数据:', state.purchasePlanData.length, '条记录，待审批:', pendingCount, '条');
					
					updateHomeThree();
				} else {
					console.warn('采购计划数据响应异常:', res);
					state.purchasePlanData = [];
					updateHomeThree();
				}
			} catch (error) {
				console.error('加载采购计划数据失败:', error);
				state.purchasePlanData = [];
				updateHomeThree();
			}
		};

		// 更新快捷导航工具数据
		const updateHomeThree = () => {
			// 更新本月销售额
			const monthlyTotal = state.salesData.monthly.reduce((sum: number, item: any) => sum + Number(item.actual_amount || 0), 0);
			state.homeThree[0].value = monthlyTotal.toFixed(2) + '元';

			// 更新生产计划数量
			const productionCount = state.productionData.yearly.length;
			state.homeThree[1].value = productionCount + '个';

			// 更新设备数量
			const deviceCount = state.deviceData.length;
			state.homeThree[2].value = deviceCount + '个';

			// 更新财务统计
			const totalAmount = state.budgetData.reduce((sum: number, item: any) => sum + Number(item.amount || 0), 0);
			state.homeThree[3].value = totalAmount.toFixed(2) + '元';

			// 更新待审批设备数量
			const pendingCount = state.maintenanceData.filter((item: any) => item.status === 1).length;
			state.homeThree[4].value = pendingCount + '个';
			
			// 更新待审批采购数量
			const pendingPurchaseCount = state.purchasePlanData.filter((item: any) => 
				item.status === 0 || item.status === '0' || item.status === 'pending' || item.status === '待审批'
			).length;
			state.homeThree[5].value = pendingPurchaseCount + '个';

			// 更新供应商数量
			const supplierCount = state.supplierData.length;
			state.homeThree[6].value = supplierCount + '个';

			// 更新供应商商品数量
			const productCount = state.supplierProductData.length;
			state.homeThree[7].value = productCount + '个';
		};

		// 获取销售业绩数据
		const loadSalesData = async () => {
			try {
				const res = await getSalesPerformance({
					page: 1,
					limit: 9999,
					ordering: '-period'
				});
				if (res.data) {
					const now = new Date();
					const currentMonth = now.getMonth() + 1;
					const currentYear = now.getFullYear();

					// 处理月度数据
					state.salesData.monthly = res.data.filter((item: any) => {
						const date = new Date(item.period);
						return date.getMonth() + 1 === currentMonth && date.getFullYear() === currentYear;
					});

					// 处理年度数据
					state.salesData.yearly = res.data.filter((item: any) => {
						const date = new Date(item.period);
						return date.getFullYear() === currentYear;
					});

					updateHomeOne();
					updateHomeThree();
				}
			} catch (error) {
				console.error('加载销售数据失败:', error);
			}
		};

		// 获取生产计划数据
		const loadProductionData = async () => {
			try {
				const res = await getProductionPlan({
					page: 1,
					limit: 9999,
					ordering: '-create_datetime'
				});
				if (res.data) {
					const now = new Date();
					const currentMonth = now.getMonth() + 1;
					const currentYear = now.getFullYear();

					// 处理月度数据
					state.productionData.monthly = res.data.filter((item: any) => {
						const date = new Date(item.start_date);
						return date.getMonth() + 1 === currentMonth && date.getFullYear() === currentYear;
					});

					// 处理年度数据
					state.productionData.yearly = res.data.filter((item: any) => {
						const date = new Date(item.start_date);
						return date.getFullYear() === currentYear;
					});

					updateHomeOne();
					updateHomeThree();
				}
			} catch (error) {
				console.error('加载生产计划数据失败:', error);
			}
		};

		

		// 获取库存预警数据
		const loadMaterialData = async () => {
			try {
				const res = await getMaterialList({
					page: 1,
					limit: 9999
				});
				if (res.data) {
					state.materialData = res.data;
					updateHomeThree();
				}
			} catch (error) {
				console.error('加载库存数据失败:', error);
			}
		};

		// 更新首页顶部卡片数据
		const updateHomeOne = () => {
			// 更新订单统计信息
			const monthlyTotal = state.salesData.monthly.reduce((sum: number, item: any) => sum + Number(item.actual_amount || 0), 0);
			const lastMonthTotal = state.salesData.monthly.reduce((sum: number, item: any) => sum + Number(item.target_amount || 0), 0);
			const orderGrowth = lastMonthTotal ? ((monthlyTotal - lastMonthTotal) / lastMonthTotal * 100).toFixed(2) : '0';
			
			state.homeOne[0].num1 = monthlyTotal.toFixed(2);
			state.homeOne[0].num2 = orderGrowth;
			state.homeOne[0].color1 = Number(orderGrowth) >= 0 ? '#6690F9' : '#FF6462';

			// 更新月度计划信息
			const monthlyPlanTotal = state.productionData.monthly.reduce((sum: number, item: any) => sum + Number(item.actual_quantity || 0), 0);
			const monthlyPlanTarget = state.productionData.monthly.reduce((sum: number, item: any) => sum + Number(item.plan_quantity || 0), 0);
			const monthlyPlanGrowth = monthlyPlanTarget ? ((monthlyPlanTotal - monthlyPlanTarget) / monthlyPlanTarget * 100).toFixed(2) : '0';

			state.homeOne[1].num1 = monthlyPlanTotal.toFixed(2);
			state.homeOne[1].num2 = monthlyPlanGrowth;
			state.homeOne[1].color1 = Number(monthlyPlanGrowth) >= 0 ? '#6690F9' : '#FF6462';

			// 更新年度计划信息
			const yearlyPlanTotal = state.productionData.yearly.reduce((sum: number, item: any) => sum + Number(item.actual_quantity || 0), 0);
			const yearlyPlanTarget = state.productionData.yearly.reduce((sum: number, item: any) => sum + Number(item.plan_quantity || 0), 0);
			const yearlyPlanGrowth = yearlyPlanTarget ? ((yearlyPlanTotal - yearlyPlanTarget) / yearlyPlanTarget * 100).toFixed(2) : '0';

			state.homeOne[2].num1 = yearlyPlanTotal.toFixed(2);
			state.homeOne[2].num2 = yearlyPlanGrowth;
			state.homeOne[2].color1 = Number(yearlyPlanGrowth) >= 0 ? '#6690F9' : '#FF6462';

			// 更新访问统计信息
			const now = new Date();
			const currentMonth = now.getMonth() + 1;
			const lastMonth = currentMonth === 1 ? 12 : currentMonth - 1;
			const currentYear = now.getFullYear();
			const lastMonthYear = currentMonth === 1 ? currentYear - 1 : currentYear;

			// 获取本月和上月的数据
			const thisMonthVisits = state.salesData.monthly.length + 
				state.productionData.monthly.length;

			const lastMonthData = [
				...state.salesData.yearly,
				...state.productionData.yearly
			].filter(item => {
				const date = new Date(item.period || item.start_date);
				return date.getMonth() + 1 === lastMonth && date.getFullYear() === lastMonthYear;
			});

			const lastMonthVisits = lastMonthData.length;
			const visitGrowth = lastMonthVisits ? ((thisMonthVisits - lastMonthVisits) / lastMonthVisits * 100).toFixed(2) : '0';

			state.homeOne[3].num1 = thisMonthVisits;
			state.homeOne[3].num2 = visitGrowth;
			state.homeOne[3].color1 = Number(visitGrowth) >= 0 ? '#6690F9' : '#FF6462';
		};

		// 折线图
		const initLineChart = () => {
			if (global.homeChartOne) {
				global.homeChartOne.dispose();
			}
			global.homeChartOne = <any>echarts.init(homeLineRef.value, state.charts.theme);
			
			// 处理销售数据
			const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
			const actualData = new Array(12).fill(0);
			const targetData = new Array(12).fill(0);

			state.salesData.yearly.forEach((item: any) => {
				const date = new Date(item.period);
				const month = date.getMonth();
				actualData[month] += Number(item.actual_amount || 0);
				targetData[month] += Number(item.target_amount || 0);
			});

			const option = {
				backgroundColor: state.charts.bgColor,
				title: {
					text: '销售业绩趋势',
					x: 'left',
					textStyle: { fontSize: '15', color: state.charts.color },
				},
				grid: { top: 70, right: 20, bottom: 30, left: 30 },
				tooltip: { trigger: 'axis' },
				legend: { data: ['实际销售额', '目标销售额'], right: 0 },
				xAxis: {
					data: months,
				},
				yAxis: [
					{
						type: 'value',
						name: '金额',
						splitLine: { show: true, lineStyle: { type: 'dashed', color: '#f5f5f5' } },
					},
				],
				series: [
					{
						name: '实际销售额',
						type: 'line',
						symbolSize: 6,
						symbol: 'circle',
						smooth: true,
						data: actualData,
						lineStyle: { color: '#fe9a8b' },
						itemStyle: { color: '#fe9a8b', borderColor: '#fe9a8b' },
						areaStyle: {
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
								{ offset: 0, color: '#fe9a8bb3' },
								{ offset: 1, color: '#fe9a8b03' },
							]),
						},
					},
					{
						name: '目标销售额',
						type: 'line',
						symbolSize: 6,
						symbol: 'circle',
						smooth: true,
						data: targetData,
						lineStyle: { color: '#9E87FF' },
						itemStyle: { color: '#9E87FF', borderColor: '#9E87FF' },
						areaStyle: {
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
								{ offset: 0, color: '#9E87FFb3' },
								{ offset: 1, color: '#9E87FF03' },
							]),
						},
					},
				],
			};
			global.homeChartOne.setOption(option);
			state.myCharts.push(global.homeChartOne);
		};

		// 饼图
		const initPieChart = () => {
			if (global.homeChartTwo) {
				global.homeChartTwo.dispose();
			}
			global.homeChartTwo = <any>echarts.init(homePieRef.value, state.charts.theme);
			const option = {
				backgroundColor: state.charts.bgColor,
				title: {
					text: '生产计划完成情况',
					x: 'left',
					textStyle: { fontSize: '15', color: state.charts.color },
				},
				tooltip: {
					trigger: 'item',
					formatter: '{a} <br/>{b} : {c} ({d}%)',
				},
				series: [
					{
						name: '生产计划',
						type: 'pie',
						radius: '70%',
						center: ['50%', '50%'],
						data: [
							{ value: state.productionData.yearly.filter((item: any) => item.status === 1).length, name: '未开始' },
							{ value: state.productionData.yearly.filter((item: any) => item.status === 2).length, name: '进行中' },
							{ value: state.productionData.yearly.filter((item: any) => item.status === 3).length, name: '已完成' },
							{ value: state.productionData.yearly.filter((item: any) => item.status === 4).length, name: '已取消' },
						],
						emphasis: {
						itemStyle: {
								shadowBlur: 10,
								shadowOffsetX: 0,
								shadowColor: 'rgba(0, 0, 0, 0.5)',
							},
						},
					},
				],
			};
			global.homeChartTwo.setOption(option);
			state.myCharts.push(global.homeChartTwo);
		};

		

		// 获取订单数据
		const loadOrderData = async () => {
			try {
				const res = await getOrderList({
					page: 1,
					limit: 9999
				});
				if (res.data) {
					state.orderData = res.data;
				}
			} catch (error) {
				console.error('加载订单数据失败:', error);
			}
		};

		// 初始化柱形图
		const initBarChart = () => {
			// 确保引用元素存在
			if (!homeBarRef.value) {
				console.warn('柱状图容器元素未准备好，延迟初始化');
				nextTick(() => {
					initBarChart();
				});
				return;
			}

			if (global.homeChartThree) {
				global.homeChartThree.dispose();
			}
			global.homeChartThree = <any>echarts.init(homeBarRef.value, state.charts.theme);

			// 处理订单数据
			const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
			const monthlyData = new Array(12).fill(0);
			
			// 获取当前年份
			const currentYear = new Date().getFullYear();
			
			if (state.orderData && state.orderData.length > 0) {
				state.orderData.forEach((item: any) => {
					// 已完成状态为值 3
					if (item.status === 3) {
						try {
							const date = new Date(item.create_datetime);
							// 只统计当前年的数据
							if (date.getFullYear() === currentYear) {
								const month = date.getMonth();
								const amount = Number(item.total_amount || 0);
								if (!isNaN(amount)) {
									monthlyData[month] += amount;
								}
							}
						} catch (err) {
							console.error('处理订单日期出错:', err);
						}
					}
				});
			}

			// 根据屏幕宽度调整布局
			const isSmallScreen = window.innerWidth < 768;
			const bottomMargin = isSmallScreen ? 60 : 50;
			const labelRotate = isSmallScreen ? 60 : 45;

			const option = {
				backgroundColor: state.charts.bgColor,
				title: {
					text: `${currentYear}年已完成订单金额统计`,
					x: 'left',
					textStyle: { fontSize: '15', color: state.charts.color },
				},
				tooltip: {
					trigger: 'axis',
					axisPointer: { type: 'shadow' },
					formatter: '{b} <br/>{a} : {c} 元'
				},
				grid: { 
					top: 70, 
					right: 20, 
					bottom: bottomMargin, 
					left: 60,
					containLabel: true
				},
				xAxis: [{
					type: 'category',
					data: months,
					axisLabel: { 
						interval: 0, 
						rotate: labelRotate,
						margin: 10,
						color: state.charts.color,
						fontSize: 12,
						align: 'center'
					},
					axisTick: {
						alignWithLabel: true
					}
				}],
				yAxis: [{
					type: 'value',
					name: '金额',
					nameLocation: 'middle',
					nameGap: 40,
					nameTextStyle: {
						color: state.charts.color,
						fontSize: 12
					},
					axisLabel: {
						formatter: '{value} 元',
						color: state.charts.color
					},
					splitLine: { show: true, lineStyle: { type: 'dashed', color: '#f5f5f5' } }
				}],
				series: [{
					name: '订单金额',
					type: 'bar',
					barWidth: isSmallScreen ? '60%' : '50%',
					data: monthlyData.map(value => value.toFixed(2)),
					label: {
						show: true,
						position: 'top',
						formatter: '{c} 元',
						fontSize: 11,
						color: '#188df0'
					},
					itemStyle: {
						color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
							{ offset: 0, color: '#83bff6' },
							{ offset: 0.5, color: '#188df0' },
							{ offset: 1, color: '#188df0' }
						])
					},
					emphasis: {
						itemStyle: {
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
								{ offset: 0, color: '#2378f7' },
								{ offset: 0.7, color: '#2378f7' },
								{ offset: 1, color: '#83bff6' }
							])
						}
					}
				}]
			};
			global.homeChartThree.setOption(option);
			state.myCharts.push(global.homeChartThree);
		};

		// 初始化 echarts
		const initEcharts = () => {
			// 确保所有引用元素都存在
			if (!homeLineRef.value || !homePieRef.value || !homeBarRef.value) {
				console.warn('图表容器元素未准备好，延迟初始化');
				nextTick(() => {
					initEcharts();
				});
				return;
			}
			initLineChart();
			initPieChart();
			initBarChart();
		};

		// 清理所有图表
		const clearCharts = () => {
			if (global.homeChartOne) {
				global.homeChartOne.dispose();
				global.homeChartOne = null;
			}
			if (global.homeChartTwo) {
				global.homeChartTwo.dispose();
				global.homeChartTwo = null;
			}
			if (global.homeChartThree) {
				global.homeChartThree.dispose();
				global.homeChartThree = null;
			}
			state.myCharts = [];
		};

		// 加载所有数据并初始化图表
		const loadAllData = async () => {
			try {
				console.log('开始加载所有数据...');
				// 重置数据状态
				state.salesData.monthly = [];
				state.salesData.yearly = [];
				state.productionData.monthly = [];
				state.productionData.yearly = [];
				
				state.materialData = [];
				state.supplierData = [];
				state.supplierProductData = [];
				state.deptData = [];
				state.deviceData = [];
				state.userData = [];
				state.maintenanceData = [];
				state.budgetData = [];
				state.orderData = [];
				state.purchasePlanData = []; // 确保清空采购计划数据

				// 清理旧图表
				clearCharts();

				await Promise.all([
					loadSalesData(),
					loadProductionData(),
					loadMaterialData(),
					loadSupplierData(),
					loadDeptData(),
					loadDeviceData(),
					loadUserData(),
					loadMaintenanceData(),
					loadBudgetData(),
					loadPurchasePlanData(),
					loadOrderData()
				]);

				console.log('所有数据加载完成，待审批采购计划数量:', state.purchasePlanData.filter(item => item.status === 0).length);
				
				nextTick(() => {
					initEcharts();
				});
			} catch (error) {
				console.error('加载数据失败:', error);
			}
		};

		// 页面加载时
		onMounted(() => {
			loadAllData();
			// 添加窗口大小变化事件监听
			window.addEventListener('resize', onResize);
		});

		// 监听布局配置
		watch(
			() => themeConfig.value.layout,
			() => {
				nextTick(() => {
					initEcharts();
				});
			}
		);

		// 监听窗口大小改变
		const onResize = () => {
			// 使用 state.myCharts 数组进行批量调整
			state.myCharts.forEach(chart => {
				if (chart) {
					chart.resize();
				}
			});
			
			// 确保特别关注柱状图的重绘
			if (global.homeChartThree) {
				// 先调整大小
				global.homeChartThree.resize();
				
				// 延迟一点重新应用选项，确保在调整后图表正确渲染
				setTimeout(() => {
					const currentOption = global.homeChartThree.getOption();
					// 调整底部边距，确保在小屏幕上有足够空间显示月份
					if (window.innerWidth < 768) {
						currentOption.grid[0].bottom = 60;
						currentOption.xAxis[0].axisLabel.rotate = 60;
					} else {
						currentOption.grid[0].bottom = 50;
						currentOption.xAxis[0].axisLabel.rotate = 45;
					}
					global.homeChartThree.setOption(currentOption);
				}, 100);
			}
		};

		// 页面激活时
		onActivated(() => {
			// 当页面被重新激活时，重新加载数据和图表
			loadAllData();
			onResize();
		});

		// 组件销毁前清理资源
		onBeforeUnmount(() => {
			clearCharts();
			window.removeEventListener('resize', onResize);
		});

		// 添加路由跳转处理函数
		const handleNavClick = (path: string) => {
			router.push(path);
		};

		// 导出单个图表
		const handleExportCommand = (command: string) => {
			switch (command) {
				case 'line':
					exportChart(global.homeChartOne, '销售业绩趋势图');
					break;
				case 'pie':
					exportChart(global.homeChartTwo, '生产计划完成情况图');
					break;
				case 'bar':
					exportChart(global.homeChartThree, '已完成订单金额统计图');
					break;
				default:
					ElMessage.warning('未知的图表类型');
			}
		};

		// 导出所有图表
		const exportAllCharts = () => {
			try {
				exportChart(global.homeChartOne, '销售业绩趋势图');
				exportChart(global.homeChartTwo, '生产计划完成情况图');
				exportChart(global.homeChartThree, '已完成订单金额统计图');
				
				ElNotification({
					title: '导出成功',
					message: '所有图表已成功导出',
					type: 'success',
				});
			} catch (error) {
				console.error('导出图表失败:', error);
				ElMessage.error('导出图表失败');
			}
		};

		// 导出图表为图片
		const exportChart = (chart: any, title: string) => {
			if (!chart) {
				ElMessage.warning('图表未初始化');
				return;
			}
			
			try {
				// 获取图表的base64图片数据
				const imgData = chart.getDataURL({
					type: 'png',
					pixelRatio: 2,
					backgroundColor: '#fff'
				});
				
				// 创建一个下载链接
				const link = document.createElement('a');
				link.download = `${title}_${new Date().toLocaleDateString()}.png`;
				link.href = imgData;
				document.body.appendChild(link);
				link.click();
				document.body.removeChild(link);
				
				ElMessage.success(`"${title}"导出成功`);
			} catch (error) {
				console.error('导出图表失败:', error);
				ElMessage.error(`"${title}"导出失败`);
			}
		};

		return {
			homeLineRef,
			homePieRef,
			homeBarRef,
			handleNavClick,
			handleExportCommand,
			exportAllCharts,
			exportChart,
			...toRefs(state),
		};
	},
});
</script>

<style scoped lang="scss">
$homeNavLengh: 8;
.home-container {
	overflow: hidden;
	
	// 导出工具栏样式
	.chart-export-toolbar {
		display: flex;
		justify-content: flex-end;
		margin-bottom: 15px;
		padding: 8px 16px;
		background-color: var(--el-color-white);
		border-radius: 4px;
		box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
		
		.el-button {
			margin-left: 10px;
		}
		
		.el-dropdown {
			margin-left: 10px;
		}
	}
	
	.home-card-one,
	.home-card-two,
	.home-card-three {
		.home-card-item {
			width: 100%;
			height: 130px;
			border-radius: 4px;
			transition: all ease 0.3s;
			padding: 20px;
			overflow: hidden;
			background: var(--el-color-white);
			color: var(--el-text-color-primary);
			border: 1px solid var(--next-border-color-light);
			&:hover {
				box-shadow: 0 2px 12px var(--next-color-dark-hover);
				transition: all ease 0.3s;
			}
			&-icon {
				width: 70px;
				height: 70px;
				border-radius: 100%;
				flex-shrink: 1;
				i {
					color: var(--el-text-color-placeholder);
				}
			}
			&-title {
				font-size: 15px;
				font-weight: bold;
				height: 30px;
			}
		}
	}
	.home-card-one {
		@for $i from 0 through 3 {
			.home-one-animation#{$i} {
				opacity: 0;
				animation-name: error-num;
				animation-duration: 0.5s;
				animation-fill-mode: forwards;
				animation-delay: calc($i/10) + s;
			}
		}
	}
	.home-card-two,
	.home-card-three {
		.home-card-item {
			height: 400px;
			width: 100%;
			overflow: hidden;
			.home-monitor {
				height: 100%;
				.flex-warp-item {
					width: 25%;
					height: 111px;
					display: flex;
					.flex-warp-item-box {
						margin: auto;
						text-align: center;
						color: var(--el-text-color-primary);
						display: flex;
						border-radius: 5px;
						background: var(--next-bg-color);
						cursor: pointer;
						transition: all 0.3s ease;
						&:hover {
							background: var(--el-color-primary-light-9);
							transition: all 0.3s ease;
						}
					}
					@for $i from 0 through $homeNavLengh {
						.home-animation#{$i} {
							opacity: 0;
							animation-name: error-num;
							animation-duration: 0.5s;
							animation-fill-mode: forwards;
							animation-delay: calc($i/10) + s;
						}
					}
				}
			}
		}
	}
	
	// 小屏幕适配
	@media screen and (max-width: 768px) {
		.home-card-three {
			.home-card-item {
				height: 450px; // 增加高度以适应更多的底部空间
			}
		}
	}
}
</style>
